package com.bussanq.api.k8s.k8s;

import io.fabric8.kubernetes.client.ConfigBuilder;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import org.apache.log4j.Logger;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

/**
 * K8s Client
 * @author lizh
 * @date 2019/9/14
 */
public class K8sService {
	private static KubernetesClient client;
	private static final Logger log = Logger.getLogger(PodService.class);
	static {
		io.fabric8.kubernetes.client.Config config = new ConfigBuilder().withMasterUrl("https://10.2.111.56:6443").build();
		client = new DefaultKubernetesClient(config);//使用默认的就足够了
		log.info("初始化client");
//		ServiceList services = client.services().inNamespace("default").list();
	}

	public KubernetesClient getClient(){
		return client;
	}

	/**
	 * 字符串参数执行 apply 命令
	 * @param yml
	 * @return
	 */
	public String applyByStr(String yml){
		InputStream stream = new ByteArrayInputStream(yml.getBytes());
		return apply(stream);
	}

	/**
	 * 工程目录下读取文件执行 apply 命令
	 * @param filePath
	 * @return
	 */
	public String applyByFile(String filePath){
		ClassLoader ret = Thread.currentThread().getContextClassLoader();
		ret = ret != null ? ret : getClass().getClassLoader();
		InputStream stream = ret.getResourceAsStream(filePath);
		return apply(stream);
	}

	/**
	 * 本地目录下读取文件执行 apply 命令
	 * @param filePath
	 * @return
	 */
	public String applyByLocalFile(String filePath){
		String res = "";
		InputStream stream;
		try {
			stream = new FileInputStream(filePath);
			res = apply(stream);
		} catch (FileNotFoundException e) {
			log.error("",e);
			res = "apply failed";
		}
		return res;
	}

	/**
	 * 执行 apply 命令
	 * @param is
	 * @return
	 */
	public String apply(InputStream is){
		String res = "";
		try {
			client.load(is).createOrReplace();
			res = "apply success";
		} catch (Exception e) {
			log.error("",e);
			res = "apply failed";
		}
		return res;
	}

}
